package com.flymobi.mshop.activity;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.widget.AdapterView.OnItemSelectedListener;

import com.flymobi.mshop.R;
import com.flymobi.mshop.adapter.ImageAdapter;
import com.flymobi.mshop.util.ImageUtil;
import com.flymobi.mshop.util.ShopCarVo;
import com.flymobi.mshop.util.ShopCarVo.CurPropValueVo;
import com.flymobi.mshop.util.ShopCarVo.Prod;
import com.flymobi.mshop.util.service.IService;
import com.flymobi.mshop.util.service.ProductService;

/**
 * 
 * @author 余鹏
 */
public class BuyShopping extends CommonActivity implements
		ViewSwitcher.ViewFactory {
	private ProgressDialog mydialog;
	private String id;
	private Map<String, Object> prod;
	private TextView txtName;
	private TextView txtCode;
	private TextView txtSalePrice;
	private WebView webIntro;
	private LinearLayout addLinearLayout;
	static final String encoding = "utf-8";
	static final String mimeType = "text/html";
	private Button btnAdd;
	Gallery gallery;
	AlertDialog dlg;
	int can = 0;
	private TextView txtSalePrices;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.shoppingdetail);
		gallery = (Gallery) this.findViewById(R.id.gallery);
		id = (String) (this.getIntent().getExtras().getString("id"));
		System.out.println("id=" + id);
		txtName = (TextView) findViewById(R.id.txtName);
		txtCode = (TextView) findViewById(R.id.txtCode);
		txtSalePrice = (TextView) findViewById(R.id.txtSalePrice);
		txtSalePrices = (TextView) findViewById(R.id.txtSalePrices);
		webIntro = (WebView) findViewById(R.id.webIntro);
		addLinearLayout = (LinearLayout) findViewById(R.id.addLinearLayout);
		btnAdd = (Button) findViewById(R.id.addShopping);
		try {
			getProd(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		btnAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				can = 1;
				ShopCarVo scv = addProd();
				LayoutInflater factory = LayoutInflater.from(BuyShopping.this);
				final View DialogView = factory.inflate(R.layout.shop, null);
				dlg = new AlertDialog.Builder(BuyShopping.this).setTitle("请选择")
						.setView(DialogView).setPositiveButton("去结账",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										mydialog = ProgressDialog.show(
												BuyShopping.this, null,
												"数据加载中...", true);
										new Thread() {
											public void run() {
												try {
													sleep(3000);
													Message msg = new Message();
													msg.what = 2;
													hdl.sendMessage(msg);
												} catch (Exception e) {
													e.printStackTrace();
												} finally {
													mydialog.dismiss();
												}
											}
										}.start();
									}
								}).setNegativeButton("继续购物",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Intent intent = new Intent();
										// intent.putExtra(name, value)
										intent.setClass(BuyShopping.this,
												Main.class);
										BuyShopping.this.startActivity(intent);
										dlg.dismiss();
										return;
									}
								}).create();
				dlg.show();
			}
		});
	}

	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		return i;
	}

	private CurPropValueVo cpvC = null;
	private CurPropValueVo cpvY = null;

	public ShopCarVo addProd() {
		ShopCarVo scv = ShopCarVo.getInstance();
		ShopCarVo.Prod prod = ShopCarVo.getInstance().new Prod();
		if (id == null || id.equals("")) {
			Toast.makeText(BuyShopping.this, "网络连接错误！", 3000).show();
			return null;
		}
		long lo = new Long(id);
		Set<Prod> p = scv.getProdList();
		for (Prod prod2 : p) {
			if (prod2.getId() == lo) {
				prod2.setCount(prod2.getCount() + 1);
			}
		}
		prod.setId(lo);
		prod.setCount(1);
		prod.setTime(new Date());
		Map<String, Object> map = new HashMap<String, Object>();
		Set<CurPropValueVo> set = new HashSet<CurPropValueVo>();
		if (cpvC != null) {
			set.add(cpvC);
		}
		if (cpvY != null) {
			set.add(cpvY);
		}
		prod.setCurPropValueList(set);
		map.put("id", lo);
		map.put("count", 1);
		map.put("name", name);
		map.put("code", code);
		map.put("saleprice", saleprice);
		prod.setProd(map);
		scv.add(prod);
		return scv;
	}

	private Spinner value;
	String name;
	String code;
	String saleprice;
	Handler hdl = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				mydialog.dismiss();
				final String[] imgPathList = (String[]) prod.get("imgList");
				name = prod.get("name").toString();
				code = prod.get("code").toString();
				saleprice = prod.get("saleprice").toString();
				String intro = prod.get("intro").toString();
				Map<String, String[]> propValueList = (Map<String, String[]>) prod
						.get("propValueList");
				ImageAdapter adapter = new ImageAdapter(BuyShopping.this,
						imgPathList);
				gallery.setAdapter(adapter);
				gallery
						.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								BitmapDrawable bm = new BitmapDrawable(
										ImageUtil
												.getHttpBitmap(IService.serverUrl
														+ imgPathList[arg2]));
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								BitmapDrawable bm = new BitmapDrawable(
										ImageUtil
												.getHttpBitmap(IService.serverUrl
														+ imgPathList[0]));
							}
						});
				for (String key : propValueList.keySet()) {
					TextView prop = new TextView(BuyShopping.this);
					prop.setTextColor(R.color.heise);
					prop.setTextSize(20);
					prop.setText(key);
					final String[] valueArray = propValueList.get(key);
					value = new Spinner(BuyShopping.this);
					ArrayAdapter<String> valueAdp = new ArrayAdapter<String>(
							BuyShopping.this,
							android.R.layout.simple_spinner_item, valueArray);
					valueAdp
							.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					value.setAdapter(valueAdp);
					value
							.setOnItemSelectedListener(new OnItemSelectedListener() {
								@Override
								public void onItemSelected(AdapterView<?> arg0,
										View arg1, int arg2, long arg3) {
									;
								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {

									;
								}
							});
					addLinearLayout.addView(prop);
					addLinearLayout.addView(value);
					if (key == "尺码") {
						System.out.println("尺码" + key);
						cpvC.setName("尺码");
						cpvC.setValue(value.toString());
					}
					if (key == "颜色") {
						System.out.println("颜色" + key);
						cpvY.setName("颜色");
						cpvY.setValue(value.toString());
					}

				}
				gallery.setUnselectedAlpha(100);
				txtName.setText("商品名称" + name);
				webIntro.loadDataWithBaseURL(null, intro, mimeType, encoding,
						null);
				txtCode.setText("商品编号：" + code);
				txtSalePrice.setText("商品价格：");
				txtSalePrices.setText("¥" + saleprice);
			}
			if (msg.what == 2) {
				Intent intent = new Intent();
				Main.WEN = 2;
				intent.setClass(BuyShopping.this, Main.class);
				BuyShopping.this.startActivity(intent);
			}
			return;
		};
	};

	public void getProd(final String id) {
		mydialog = ProgressDialog
				.show(BuyShopping.this, null, "数据加载中...", true);
		new Thread() {
			public void run() {
				try {
					prod = ProductService.get(id);
					Message msg = new Message();
					msg.what = 1;
					hdl.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
}